package main

import (
	"context"
	"flag"
	"fmt"
	"gugojudger/controller"
	"gugojudger/env"
	"gugojudger/mq"
	"gugojudger/utils/ojchannel"
	"gugojudger/utils/osutils"
	"log"
	"os"
	"time"
)

func main() {
	//	var workpath string
	var maxjudger int
	var vjudger bool

	//	flag.StringVar(&workpath, "workpath", "/tmp/gogujudger/", "the path for save log and target file")
	flag.IntVar(&maxjudger, "maxjudge", 20, "set the max size of judger")
	flag.BoolVar(&vjudger, "vjudger", true, "enable the virtual judge")

	flag.Parse()

	//	env.SetWorkPath(workpath)
	env.SetMaxJudge(maxjudger)

	workpath := env.GetWorkPath()

	fmt.Println(workpath)
	if ie, _ := osutils.PathExists(workpath); !ie {
		err := os.Mkdir(workpath, 0755)
		if err != nil {
			fmt.Println("Create target dir failed :" + err.Error())
			return
		}
	}

	LogPath := workpath + time.Now().Format("2006-01-02") + ".log"

	var ChLog = ojchannel.NewChannel()
	defer func() {
		ChLog.SafeClose()
	}()

	//开始消息队列获取数据
	ctxMQ, mqCancel := context.WithCancel(env.CtxRoot())
	defer mqCancel()
	go mq.StartMQConsume(ctxMQ)

	FileLog, err := os.OpenFile(LogPath, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0777)
	fmt.Println("Created runtime Log at " + FileLog.Name() + "\t max judge:" + fmt.Sprintf("%d", maxjudger))
	if err != nil {
		fmt.Println(err.Error())
	}
	defer FileLog.Close()

	Logger := log.New(FileLog, "", log.LstdFlags)

	//write the flag while stating
	go func() {
		ChLog.C <- ojchannel.FastLog(1, fmt.Sprintf("%s%s", "Start with Variable :", flag.Args()))
	}()

	if vjudger {
		fmt.Println("Http Servers has been started.")
		go controller.StartHttpControl(ChLog)
	}

	for {
		log := <-ChLog.C
		switch log.Level {
		case 1:
			{
				Logger.SetPrefix("[INFO]")
				Logger.Printf("\t%s\n", log.Message)
				break
			}
		case 2:
			{
				Logger.SetPrefix("[WARN]")
				Logger.Printf("\t%s\n", log.Message)
				break
			}
		case 3:
			{
				Logger.SetPrefix("[EROR]")
				Logger.Printf("\t%s\n", log.Message)
				break
			}
		//no case 4 ,it will be reserved
		case 5:
			{
				Logger.SetPrefix("[FAIL]")
				Logger.Fatalf("\t%s\n", log.Message)
			}
		}
	}

}
